package com.rew.canteenbox.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.rew.canteenbox.R;
import com.rew.canteenbox.models.Orders;

import java.util.List;

/**
 *  订单列表Adapter.
 *
 * Created by HuiWen Ren on 2016/11/14.
 */
public class BuyListAdapter extends ArrayAdapter<Orders>{

    private int resourceId;

    public BuyListAdapter(Context context, int textViewResourceId,
                          List<Orders> objects) {
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Orders orders = getItem(position);
        View view;
        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            view = LayoutInflater.from(getContext()).inflate(resourceId, null);
            // 对应布局.
            viewHolder.dishesImage = (ImageView) view.findViewById
                    (R.id.img_buy);
            viewHolder.dishesName = (TextView) view.findViewById
                    (R.id.tv_buy_name);
            viewHolder.addUpPrice = (TextView) view.findViewById
                    (R.id.tv_buy_price);
            viewHolder.Num = (TextView) view.findViewById
                    (R.id.tv_buy_num);
            view.setTag(viewHolder); // 将ViewHolder存储在View中.
        } else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag(); // 重新获取ViewHolder.
        }
        // 设置资源.
        viewHolder.dishesImage.setImageResource(orders.getDishes().getPicId());
        viewHolder.dishesName.setText(orders.getDishes().getDishName());
        // 获取价格.
        double price = Double.valueOf(orders.getDishes().getDishPrice());
        // 获取数量.
        int Num = orders.getNum();
        double addUp = price * Num;
        // 价格格式：￥20
        viewHolder.addUpPrice.setText("￥" + Double.toString(addUp));
        // 已购数量.
        viewHolder.Num.setText("Num = " + Integer.toString(Num));

        return view;
    }

    // view类.
    class ViewHolder {
        ImageView dishesImage;
        TextView dishesName;
        TextView addUpPrice;
        TextView Num;
    }
}
